﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Events;
using HYCodeBase.WinForm;

namespace HYView
{
	internal class ShowDlgApp : IExternalApplication
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result OnShutdown(UIControlledApplication application)
		{
			if (this.m_MyForm != null && !this.m_MyForm.IsDisposed)
			{
				this.m_MyForm.Dispose();
				this.m_MyForm = null;
				application.Idling -= this.IdlingHandler;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public Result OnStartup(UIControlledApplication application)
		{
			this.m_MyForm = null;
			ShowDlgApp.ThisApp = this;
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		public void ShowForm(UIApplication uiapp)
		{
			if (this.m_MyForm == null || this.m_MyForm.IsDisposed)
			{
				if (ShowDlgApp._hWndRevit == null)
				{
					ShowDlgApp._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
				}
				this.m_MyForm = DlgModelView.GetInstance(uiapp);
				this.m_MyForm.Show(ShowDlgApp._hWndRevit);
				int wMsg = 7;
				ShowDlgApp.SendMessage(ShowDlgApp._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
				uiapp.Idling += this.IdlingHandler;
			}
		}

		public void CloseForm()
		{
			if (this.m_MyForm != null || !this.m_MyForm.IsDisposed)
			{
				this.m_MyForm.Close();
			}
		}

		public void IdlingHandler(object sender, IdlingEventArgs args)
		{
			UIApplication uiapplication = sender as UIApplication;
			if (this.m_MyForm.IsDisposed)
			{
				uiapplication.Idling -= this.IdlingHandler;
				return;
			}
			RequestId requestId = this.m_MyForm.Request.Take();
			if (requestId == RequestId.SetVisible)
			{
				RequestHandler.SetVisible(uiapplication, this.m_MyForm.es, this.m_MyForm.vis);
				return;
			}
			if (requestId == RequestId.UpdateView)
			{
				this.m_MyForm.ShowByCategory();
				this.m_MyForm.ShowByLevel();
			}
		}

		internal static ShowDlgApp ThisApp;

		public DlgModelView m_MyForm;

		public static WindowHandle _hWndRevit;
	}
}
